<?php
class HTTPRequestAdapterCurl extends RequestAdapter {

	protected $curl = false;
	protected $fp = false;

	public function sendRequest(){
		$this->_setRequest();
		return $this->_sendRequest();
	}
	public function _setRequest(){
		$this->curl = curl_init($this->uri->url);
		curl_setopt($this->curl,CURLOPT_TIMEOUT,$this->requestTimeout);
		curl_setopt($this->curl,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_NONE);
		// http verb
        if (strtoupper($this->verb) == 'PUT') {
            throw new Exception("HTTP put not implmented for Curl yet");
        }
        curl_setopt($this->curl,CURLOPT_CUSTOMREQUEST,$this->verb);

        // headers
        curl_setopt($this->curl,CURLOPT_HTTPHEADER,$this->headers);

        // general stuff
        curl_setopt($this->curl,CURLOPT_BINARYTRANSFER,true);
        curl_setopt($this->curl,CURLOPT_RETURNTRANSFER,true);
        //curl_setopt($this->curl,CURLOPT_NOBODY,1);

        // setup a callback to handle header info
        curl_setopt($this->curl,CURLOPT_HEADERFUNCTION,array($this,'_headerCallback'));

		 // post data
        if (!empty($this->body)) {
            curl_setopt($this->curl,CURLOPT_POSTFIELDS,$this->body);
        }
		//dbg($this);
	}
	public function _sendRequest(){
		$body = curl_exec($this->curl);
		if($this->fp !== false)
			fclose($this->fp);
		$details = $this->uri->toArray();
		$details['code'] = curl_getinfo($this->curl,CURLINFO_HTTP_CODE);
		$headers = new HTTPRequestHeaders($this->headers);
		$cookies = array();
		return new HTTPResponse($details,$body,$headers,$cookies);
	}
	 protected function _headerCallback($curl,$data) {
         $this->processHeader(trim($data));
		 return strlen($data);
    }
}